package com.tuandai.commons.encrypt.jdbc_api;

import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 从数据连接接口获取数据连接配置的工具类
 * Created by zhangzhenbin on 18-2-1.
 */
public class JdbcConfigLoader {
    /**
     * 从数据连接接口获取数据连接配置
     * @param url
     * @param jksLocation
     * @param jksPassword
     * @param jksAlias
     * @param jksSecret
     * @return
     * @throws IOException
     */
    public static JdbcConfig loadFromRest(String url, String jksLocation, String jksPassword, String jksAlias, String jksSecret) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(new HttpGet(url));
        InputStream is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String json = br.lines().reduce((s, s2) -> s + s2).orElse("");
        br.close();
        is.close();
        JdbcConfig jdbcConfig = new Gson().fromJson(json, JdbcConfig.class);
        String password;
        try {
            password = DbPasswordDigestUtils.decrypt(jdbcConfig.getPass());
        } catch (Exception e) {
            password = jdbcConfig.getPass();
        }
        password = JksDigestUtils.decrypt(password, jksLocation, jksPassword, jksAlias, jksSecret);
        String jdbcUrl = JksDigestUtils.decrypt(jdbcConfig.getUrl(), jksLocation, jksPassword, jksAlias, jksSecret);
        String userName = JksDigestUtils.decrypt(jdbcConfig.getDbUser(), jksLocation, jksPassword, jksAlias, jksSecret);
        jdbcConfig.setPass(password);
        jdbcConfig.setUrl(jdbcUrl);
        jdbcConfig.setDbUser(userName);
        jdbcConfig.setDriverName(getDriverNameByUrl(jdbcUrl));
        return jdbcConfig;
    }

    public static String getDriverNameByUrl(String connectionUrl) {
        if (connectionUrl.contains("jtds")) {
            return "net.sourceforge.jtds.jdbc.Driver";
        }
        if (connectionUrl.contains("sqlserver")) {
            return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        }
        if (connectionUrl.contains("mysql")) {
            return "com.mysql.jdbc.Driver";
        }
        if (connectionUrl.contains("postgresql")) {
            return "org.postgresql.Driver";
        }
        if (connectionUrl.contains("jdbc:hive2")){
            return "org.apache.hive.jdbc.HiveDriver";
        }
        if (connectionUrl.contains("jdbc:impala")){
            return "com.cloudera.impala.jdbc41.Driver";
        }
        return null;
    }
}
